#!/bin/bash
# tools to run dmctl from command line
# parameter 1: work directory
# parameter 2: master-addr port
# parameter 3: command
# parameter 4...: check output content and count

workdir=$1
master_addr=$2
cmd=$3

shift 3

PWD=$(pwd)
binary=$PWD/bin/dmctl.test
ts=$(date +"%s")
dmctl_log=$workdir/dmctl.$ts.log
pid=$$
echo "dmctl test cmd: \"$cmd\""
echo "$cmd" | $binary -test.coverprofile="$TEST_DIR/cov.$TEST_NAME.dmctl.$ts.$pid.out" DEVEL -master-addr=$master_addr > $dmctl_log 2>&1

for ((i=1; i<$#; i+=2)); do
    j=$((i+1))
    value=${!i}
    expected=${!j}
    got=$(sed "s/$value/$value\n/g" $dmctl_log | grep -c "$value")
    if [ "$got" != "$expected" ]; then
        echo "command: $cmd $value count: $got != expected: $expected"
        cat $dmctl_log
        exit 1
    fi
done

# gocovmerge doesn't support merge profiles with different modes, however atomic
# mode and count mode have the same profile format, so we need to unify cover
# mode before running gocovmerge. As coverage file is not generated synchronously,
# we will patch covermode before `make coverage`
